//
//  ShopMallVC.m
//  YBLive
//
//  Created by ybRRR on 2020/8/18.
//  Copyright © 2020 cat. All rights reserved.
//

#import "ShopMallVC.h"
#import "HXSearchBar.h"
#import "ShopMallCell.h"
#import "SDCycleScrollView.h"
#import "ShopMallClassView.h"
#import "ShopMallDetailVC.h"
#import "ShopMallSearchVC.h"
#import "OutsideGoodsDetailVC.h"
#import "CommodityDetailVC.h"
//#import "ZYTabBar.h"
#import "YBShopLayout.h"
//#import "MyCollectionVC.h"
#import "ShopHomeVC.h"
@interface ShopMallVC ()<UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate,mallClassDelegate,YBShopLayoutDeleaget>
{
    HXSearchBar *searchBars;
    UIView *collectionHeaderView;
    UIView *noDataView;
    int page;
    
    CGFloat lastContentOffset;
    
    UIView *youngView;
}
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *infoArray;
@property(nonatomic,strong)NSArray *CarouselArray;//轮播图
@property(nonatomic,strong)NSArray *classArray;//轮播图
@property(nonatomic,strong)NSString *shop_switch;//是否开通店铺

@property (nonatomic,strong) SDCycleScrollView *cycleScroll;
@property (nonatomic,strong)ShopMallClassView *mallClassView;
@property (nonatomic,strong)YBShopLayout *flow;


@end

@implementation ShopMallVC

#pragma mark--------网络请求-------------
-(void)pullInternet{
    
    [WYNetworking postWithUrl:@"Home.getShopList" Dic:@{@"p":@(page)}  Suc:^(int code, id info, NSString *msg) {
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
        if (code == 0) {
                NSArray *infoA = [info objectAtIndex:0];
                NSArray *list = [infoA valueForKey:@"list"];
                if (page == 1) {
                    [_infoArray removeAllObjects];
                    NSMutableArray *sliderMuArr = [NSMutableArray array];
                    self.CarouselArray = [infoA valueForKey:@"slide"];
                    self.classArray = [infoA valueForKey:@"shoptwoclass"];
                    self.shop_switch = [infoA valueForKey:@"shop_switch"];
                    [self createCollectionHeaderView];

                    for (NSDictionary *dic in _CarouselArray) {
                        [sliderMuArr addObject:minstr([dic valueForKey:@"slide_pic"])];
                    }
                    _cycleScroll.imageURLStringsGroup = sliderMuArr;
                }
                [_infoArray addObjectsFromArray:list];
                [_collectionView reloadData];
                if (_infoArray.count < 1) {
//                    [PublicView showTextNoData:_collectionView text1:@"暂无商品" text2:@""];
                    noDataView.hidden = NO;
                    noDataView.frame = CGRectMake(0, collectionHeaderView.height+20, _window_width, 40);

                }else{
//                    [PublicView hiddenTextNoData:_collectionView];
                    noDataView.hidden = YES;
                }
            if (list.count == 0) {
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        

        } Fail:^(id fail) {
            [_collectionView.mj_header endRefreshing];
            [_collectionView.mj_footer endRefreshing];

        }];
}
#pragma mark--------青少年模式提示------

-(void)closeYoungClick{
    [[YBYoungManager shareInstance]checkYoungStatus:YoungFrom_Center];
}
-(void)showYoungTips{
    youngView = [[UIView alloc]init];
    youngView.frame = CGRectMake(0, 0, _window_height, _window_height);
    youngView.backgroundColor = Normal_Color;
    [self.view addSubview:youngView];
    
    UILabel *titleLb = [[UILabel alloc]init];
    titleLb.font = [UIFont systemFontOfSize:14];
    titleLb.textColor = UIColor.whiteColor;
    titleLb.text = YZMsg(@"青少年模式下暂无商品信息");
    [youngView addSubview:titleLb];
    [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    UIButton *closeBtn = [UIButton buttonWithType:0];
    [closeBtn setTitle:YZMsg(@"关闭青少年模式") forState:0];
    [closeBtn setTitleColor:Pink_Cor forState:0];
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [closeBtn addTarget:self action:@selector(closeYoungClick) forControlEvents:UIControlEventTouchUpInside];
    [youngView addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(titleLb.mas_centerX);
        make.top.equalTo(titleLb.mas_bottom).offset(10);
    }];
}
-(void)removeYoungView{
    if (youngView) {
        [youngView removeFromSuperview];
        youngView = nil;
    }
}
#pragma mark--------初始化-------------
-(void)initData{
    page = 1;
    
    self.infoArray    =  [NSMutableArray array];
    self.CarouselArray = [NSMutableArray array];
    self.classArray = [NSArray array];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if ([[YBYoungManager shareInstance]youngSwitch]) {
        [self showYoungTips];
    }else{
        [self removeYoungView];
    }

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = RGBA(235, 235, 235, 1);
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeYoungView) name:@"shopYongChange" object:nil];
    [self initData];
    [self addSearchBar];
    
    [self createCollectionView];
    [self createNoDataView];

}
-(void)createNoDataView{
    noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 200, _window_width, 40)];
    noDataView.hidden = YES;
    noDataView.backgroundColor = [UIColor clearColor];
    [_collectionView addSubview:noDataView];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _window_width, 20)];
    label1.font = [UIFont systemFontOfSize:14];
    label1.text = YZMsg(@"暂无商品");
    label1.textAlignment = NSTextAlignmentCenter;
    label1.textColor = RGB_COLOR(@"#333333", 1);
    [noDataView addSubview:label1];
    noDataView.hidden = YES;
}

#pragma mark--------添加搜索条---------begin--------
- (void)addSearchBar {
    //加上 搜索栏
    searchBars = [[HXSearchBar alloc] initWithFrame:CGRectMake(10,66+statusbarHeight, _window_width-20,50)];
    searchBars.backgroundColor = [UIColor clearColor];
//    searchBars.delegate = self;
    //输入框提示
    searchBars.placeholder = YZMsg(@"请输入您要搜索的商品名称");
    //光标颜色
    searchBars.cursorColor = Pink_Cor;
    //TextField
    searchBars.searchBarTextField.layer.cornerRadius = 25;
    searchBars.searchBarTextField.layer.masksToBounds = YES;
    searchBars.searchBarTextField.backgroundColor = UIColor.whiteColor;
    //去掉取消按钮灰色背景
    searchBars.hideSearchBarBackgroundImage = YES;
    searchBars.searchBarTextField.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:searchBars];
    [[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor grayColor]];
    
    
    UIButton *searchBtn = [UIButton buttonWithType:0];
    searchBtn.frame = CGRectMake(0, 0, searchBars.width, searchBars.height);
    [searchBtn addTarget:self action:@selector(searchBarClick) forControlEvents:UIControlEventTouchUpInside];
    [searchBars addSubview:searchBtn];

}
-(void)headBtnClick{
    if ([[Config getOwnID] intValue] <= 0) {
        [PublicObj warnLogin];
        return;
    }
    ShopHomeVC *shop = [[ShopHomeVC alloc]init];
    shop.shop_name = YZMsg(@"直播小店");
    shop.shop_switch = self.shop_switch;
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:shop animated:YES];

}
-(void)collectionBtnClick{
    if ([[Config getOwnID] intValue] <= 0) {
        [PublicObj warnLogin];
        return;
    }
//    MyCollectionVC *collect = [[MyCollectionVC alloc]init];
//    [[MXBADelegate sharedAppDelegate]pushViewController:collect animated:YES];

}
-(void)searchBarClick{
    if ([[Config getOwnID] intValue] <= 0) {
        [PublicObj warnLogin];
        return;
    }

    ShopMallSearchVC *searchVC = [[ShopMallSearchVC alloc]init];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:searchVC animated:YES];
}
#pragma mark--------添加搜索条---------end--------
- (void)createCollectionHeaderView{
    if (collectionHeaderView) {
        [collectionHeaderView removeFromSuperview];
        collectionHeaderView = nil;
    }
    
    collectionHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_width*0.3*2+20)];
    collectionHeaderView.backgroundColor =  RGBA(235, 235, 235, 1);

    collectionHeaderView.clipsToBounds = YES;
    if (_CarouselArray.count > 0) {
        _cycleScroll = [[SDCycleScrollView alloc]initWithFrame:CGRectMake(10, 5, _window_width-20, _window_width*0.3)];
        _cycleScroll.delegate = self;
        _cycleScroll.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
        [collectionHeaderView addSubview:_cycleScroll];
        _cycleScroll.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _cycleScroll.autoScrollTimeInterval = 3.0;//轮播时间间隔，默认1.0秒，可自定义
        _cycleScroll.currentPageDotColor = [UIColor whiteColor];
        _cycleScroll.pageDotColor = [[UIColor whiteColor] colorWithAlphaComponent:0.4];
        _cycleScroll.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
        _cycleScroll.layer.cornerRadius = 5;
        _cycleScroll.layer.masksToBounds = YES;
        
        if (self.classArray.count > 12) {
            _mallClassView = [[ShopMallClassView alloc]initWithFrame:CGRectMake(10, _cycleScroll.bottom+5, _window_width-20, _window_width*0.3+30) andData:self.classArray];
            _mallClassView.delegate = self;
            [collectionHeaderView addSubview:_mallClassView];
            collectionHeaderView.size = CGSizeMake(_window_width, _window_width*0.3*2+40);
        }else if(self.classArray.count == 0){
            collectionHeaderView.size = CGSizeMake(_window_width, _window_width*0.3+40);

        }else{
            _mallClassView = [[ShopMallClassView alloc]initWithFrame:CGRectMake(10, _cycleScroll.bottom+5, _window_width-20, (_window_width*0.3)/2+30) andData:self.classArray];
            _mallClassView.delegate = self;
            [collectionHeaderView addSubview:_mallClassView];
            collectionHeaderView.size = CGSizeMake(_window_width, _window_width*0.3+(_window_width*0.3)/2+40);

        }
    }else{
        if (self.classArray.count > 12) {
            _mallClassView = [[ShopMallClassView alloc]initWithFrame:CGRectMake(10, 0, _window_width-20, _window_width*0.3+20) andData:self.classArray];
            _mallClassView.delegate = self;
            [collectionHeaderView addSubview:_mallClassView];
            collectionHeaderView.size = CGSizeMake(_window_width, _window_width*0.3+40);
        }else if(self.classArray.count == 0){
            collectionHeaderView.size = CGSizeMake(0, 0);
        }else{
            _mallClassView = [[ShopMallClassView alloc]initWithFrame:CGRectMake(10, 0, _window_width-20, (_window_width*0.3)/2+30) andData:self.classArray];
            _mallClassView.delegate = self;
            [collectionHeaderView addSubview:_mallClassView];
            collectionHeaderView.size = CGSizeMake(_window_width, (_window_width*0.3)/2+40);

        }

    }

    
}
#pragma mark ============轮播图点击=============
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    NSString *uuuuuuu = minstr([_CarouselArray[index] valueForKey:@"slide_url"]);
    if ([PublicObj isUrlString:uuuuuuu]) {
        PubH5 *web = [[PubH5 alloc]init];
        web.url = uuuuuuu;
        [[YBBaseAppDelegate sharedAppDelegate] pushViewController:web animated:YES];
    }
}
-(int)getRandomCellHeight:(int)from to:(int)to{
    return (int)(from +(arc4random()%(to-from+1)));
}
-(void)createCollectionView{
        _flow = [[YBShopLayout alloc] init];
        _flow.delegate = self;
        _flow.flowLayoutStyle = 0;

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,64+50+statusbarHeight, _window_width, _window_height-64-statusbarHeight-50-ShowDiff-49) collectionViewLayout:_flow];
        _collectionView.backgroundColor =   RGBA(235, 235, 235, 1);
        _collectionView.delegate   = self;
        _collectionView.dataSource = self;
        [_collectionView registerNib:[UINib nibWithNibName:@"ShopMallCell" bundle:nil] forCellWithReuseIdentifier:@"ShopMallCell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hotHeaderV"];

        [self.view addSubview:_collectionView];

        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            page = 1;
            [self pullInternet];
        }];
        _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            page ++;
            [self pullInternet];
        }];
        [self pullInternet];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _infoArray.count;
}
- (CGSize)waterFlowLayout:(YBShopLayout *)waterFlowLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    int height =[self getRandomCellHeight:(_window_width-21)/2 + 75 to:(_window_width-21)/2 + 250];

    return CGSizeMake((_window_width-21)/2, height);
}
/** 列数*/
-(CGFloat)columnCountInWaterFlowLayout:(YBShopLayout *)waterFlowLayout{
    return 2;
}
/** 列间距*/
-(CGFloat)columnMarginInWaterFlowLayout:(YBShopLayout *)waterFlowLayout{
    return 10;
}
/** 边缘之间的间距*/
-(UIEdgeInsets)edgeInsetInWaterFlowLayout:(YBShopLayout *)waterFlowLayout{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];

    NSDictionary *subDic = _infoArray[indexPath.row];
    [PublicObj checkGoodsExistenceWithID:minstr([subDic valueForKey:@"id"]) Existence:^(int code, NSString *msg) {
        if (code == 0) {
            if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
                OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid = @"0";
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }else{
                CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                detail.goodsID = minstr([subDic valueForKey:@"id"]);
                detail.liveUid = @"0";
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }

        }else{
            [MBProgressHUD showError:msg];

        }

    }];

}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        ShopMallCell *cell = (ShopMallCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"ShopMallCell" forIndexPath:indexPath];
        NSDictionary *subDic = _infoArray[indexPath.row];
        [cell.thumbImgV sd_setImageWithURL:[NSURL URLWithString:minstr([subDic valueForKey:@"thumb"])]];
        cell.titleL.text = minstr([subDic valueForKey:@"name"]);
        cell.priceL.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"price"])];
        //type  商品类型   0 站内商品  1 外链商品
        if ([minstr([subDic valueForKey:@"type"]) isEqual:@"1"]) {
            cell.lineLb.hidden = NO;
            cell.sellCountLb.text = [NSString stringWithFormat:@"¥%@",minstr([subDic valueForKey:@"original_price"])];
        }else{
            cell.lineLb.hidden = YES;
            cell.sellCountLb.text =[NSString stringWithFormat:@"%@%@%@",YZMsg(@"已售"),minstr([subDic valueForKey:@"sale_nums"]),YZMsg(@"件")];
        }
//        cell.backgroundColor = Normal_Color;
        cell.titleL.textColor = UIColor.blackColor;
        return cell;
}
#pragma mark ================ collectionview头视图 ===============
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {

            UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"hotHeaderV" forIndexPath:indexPath];

            header.backgroundColor = [UIColor whiteColor];
            [header addSubview:collectionHeaderView];
            return header;
        }else{
            return nil;
        }
}
/** 头视图Size */
-(CGSize )waterFlowLayout:(YBShopLayout *)waterFlowLayout sizeForHeaderViewInSection:(NSInteger)section{
    if (_CarouselArray.count == 0) {
        if (self.classArray.count > 12) {
            return CGSizeMake(_window_width, _window_width*0.3+40);
        }else if(self.classArray.count == 0){
            return CGSizeMake(0, 0);

        }else{
            return CGSizeMake(_window_width, (_window_width*0.3)/2+40);
        }

    }
    if (self.classArray.count > 12) {
        return CGSizeMake(_window_width, _window_width*0.3*2+40);
    }else if(self.classArray.count == 0){
        return CGSizeMake(_window_width, _window_width*0.3+30);
    }else{
        return CGSizeMake(_window_width, _window_width*0.3+(_window_width*0.3)/2+40);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
        if (_CarouselArray.count == 0) {
            if (self.classArray.count > 12) {
                return CGSizeMake(_window_width, _window_width*0.3+40);
            }else if(self.classArray.count == 0){
                return CGSizeMake(0, 0);

            }else{
                return CGSizeMake(_window_width, (_window_width*0.3)/2+40);
            }

        }
        if (self.classArray.count > 12) {
            return CGSizeMake(_window_width, _window_width*0.3*2+40);
        }else if(self.classArray.count == 0){
            return CGSizeMake(_window_width, _window_width*0.3+30);
        }else{
            return CGSizeMake(_window_width, _window_width*0.3+(_window_width*0.3)/2+40);
        }
}

#pragma mark--------分类代理--------
-(void)selectClassData:(NSDictionary *)dic
{
    ShopMallDetailVC *detail = [[ShopMallDetailVC alloc]init];
    detail.classDic = dic;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:detail animated:YES];
}


-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    lastContentOffset = scrollView.contentOffset.y;

}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (scrollView.contentOffset.y < lastContentOffset)

    {
        [self showTabBar];

//        [self.navigationController setNavigationBarHidden:NO animated:YES];//向上

    } else if (scrollView.contentOffset.y > lastContentOffset)

    {
//        [self.navigationController setNavigationBarHidden:YES animated:YES];//向下
        [self hideTabBar];

    }

}

#pragma mark ================ 隐藏和显示tabbar ===============
- (void)hideTabBar {
    
//    if (self.tabBarController.tabBar.hidden == YES) {
//        return;
//    }
//    self.tabBarController.tabBar.hidden = YES;
//    ZYTabBar *tabbar = (ZYTabBar *)self.tabBarController.tabBar;
//    tabbar.plusBtn.hidden = YES;
}
- (void)showTabBar

{
//    if (self.tabBarController.tabBar.hidden == NO)
//    {
//        return;
//    }
//    self.tabBarController.tabBar.hidden = NO;
//    ZYTabBar *tabbar = (ZYTabBar *)self.tabBarController.tabBar;
//    tabbar.plusBtn.hidden = NO;

}

@end
